package com.zykj.thread.concurrent.lock;

import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zhoulj(周利军) [1217102780@qq.com]
 * @Module ID:   <(模块)类编号，可以引用系统设计中的类编号>
 * @Comments: <对此类的描述，可以引用系统设计中的描述>
 * @JDK version used:      <JDK1.8> 09
 * @since 2019/1/15-15:09
 */
public class ReadWriteLock {

    public static void main(String[] args) {

        final CacheData cacheData = new CacheData();
        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        cacheData.read();

                        cacheData.write(new Random().nextInt(10000));
                    }


                }
            }).start();
        }

    }
}

class CacheData {
    int data;
    java.util.concurrent.locks.ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public void read() {
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + ", 读取数据:" + data);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }finally {
            readWriteLock.readLock().unlock();
        }

    }

    public void write(int data) {
        readWriteLock.writeLock().lock();
        try {
            Thread.sleep(100);

            this.data = data;
            System.out.println(Thread.currentThread().getName()+", 写入数据：" + data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }

    }
}
